package com.guoxue.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONObject;
import com.guoxue.dao.IBaseDao;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.TapesShareVo;
import com.guoxue.domain.UserCommentVo;
import com.guoxue.model.GiftList;
import com.guoxue.model.GiveAwayGiftList;
import com.guoxue.model.RankModel;

import javassist.compiler.SyntaxError;
@Repository
public class BaseDaoImpl<T> implements IBaseDao<T> {
	@Resource
	private SessionFactory sessionFactory;  
	  
    private Session getCurrentSession() {  
        return sessionFactory.getCurrentSession();  
    }  
    public Serializable save(T o) {  
        return this.getCurrentSession().save(o);  
    }  
  
    public void delete(T o) {  
        this.getCurrentSession().delete(o);  
    }  
  
    public void update(T o) {  
        this.getCurrentSession().update(o);  
    }  
  
    public void saveOrUpdate(T o) {  
        this.getCurrentSession().saveOrUpdate(o);  
    }  
  
	@SuppressWarnings("unchecked")
	public List<T> find(String hql) { 
		getCurrentSession().clear();
        return this.getCurrentSession().createQuery(hql).list();  
    }  
  
    @SuppressWarnings("unchecked")
	public List<T> find(String hql, Object[] param) {  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        List<T> obj = q.list();
        getCurrentSession().clear();
        return obj;  
    }  
    @SuppressWarnings("unchecked")
    public List<T> find(String hql, List<Object> param) {  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.size() > 0) {  
            for (int i = 0; i < param.size(); i++) {  
                q.setParameter(i, param.get(i));  
            }  
        }  
        getCurrentSession().clear();
        return q.list();  
    }  
    @SuppressWarnings("unchecked")
    public List<T> find(String hql, Object[] param, Integer page, Integer rows) {  
        if (page == null || page < 1) {  
            page = 1;  
        }  
        if (rows == null || rows < 1) {  
            rows = 10;  
        }  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        getCurrentSession().clear();
        return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();  
    }  
    @SuppressWarnings("unchecked")
    public List<T> find(String hql, List<Object> param, Integer page, Integer rows) {  
        if (page == null || page < 1) {  
            page = 1;  
        }  
        if (rows == null || rows < 1) {  
            rows = 10;  
        }  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.size() > 0) {  
            for (int i = 0; i < param.size(); i++) {  
                q.setParameter(i, param.get(i));  
            }  
        }  
        return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();  
    }  
    @SuppressWarnings("unchecked")
    public T get(Class<T> c, Serializable id) {  
        return (T) this.getCurrentSession().get(c, id);  
    }  
  
    public T get(String hql, Object[] param) {  
        List<T> l = this.find(hql, param);  
        if (l != null && l.size() > 0) {  
            return l.get(0);  
        } else {  
            return null;  
        }  
    }  
  
    public T get(String hql, List<Object> param) {  
        List<T> l = this.find(hql, param);  
        if (l != null && l.size() > 0) {  
            return l.get(0);  
        } else {  
            return null;  
        }  
    }  
  
    public Long count(String hql) {  
        return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();  
    }  
  
    public Long count(String hql, Object[] param) {  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        return (Long) q.uniqueResult();
    }  
  
    public Long count(String hql, List<Object> param) {  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.size() > 0) {  
            for (int i = 0; i < param.size(); i++) {  
                q.setParameter(i, param.get(i));  
            }  
        }  
        return (Long) q.uniqueResult();  
    }  
  
    public Integer executeHql(String hql) {  
        return this.getCurrentSession().createQuery(hql).executeUpdate();  
    }  
  
    public Integer executeHql(String hql, Object[] param) {  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        return q.executeUpdate();  
    }  
  
    public Integer executeHql(String hql, List<Object> param) {  
        Query q = this.getCurrentSession().createQuery(hql);  
        if (param != null && param.size() > 0) {  
            for (int i = 0; i < param.size(); i++) {  
                q.setParameter(i, param.get(i));  
            }  
        }  
        return q.executeUpdate();  
    }  
    
    public Map<String,String> map(String hql,Object[] param){  
        Session session = this.getCurrentSession();  
        //返回list，list里存放的是Map对象  
        Query q = session.createSQLQuery(hql);
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        ArrayList list = (ArrayList) q.list();
        Iterator it = list.iterator();
        Map<String,String> map= new HashMap<>();
    	Object[] oc = (Object[])it.next();
    	map.put("goodsId", oc[0].toString());
    	map.put("popularityValue", oc[1].toString());
        //List companyIncomeList = session.createSQLQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); 
        return map;  
    } 
    
    public List<GiftList> GiftListObjList(String hql,Object[] param){  
        Session session = this.getCurrentSession();  
        //返回list，list里存放的是Map对象  
        Query q = session.createSQLQuery(hql);
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        ArrayList list = (ArrayList) q.list();
        Iterator it = list.iterator();
        List<GiftList> Gift= new ArrayList<>();
        while(it.hasNext()){//[37,10,null,"商品1"
        	Object[] oc = (Object[])it.next();
        	GiftList g = new GiftList();
        	g.setGiveUid(Integer.valueOf(oc[0].toString()));
        	g.setTotalNumber(oc[1].toString());
        	g.setPropIcon(oc[2].toString());
        	g.setPropName(oc[3].toString());
        	Gift.add(g);
        }
        return Gift;  
    } 
    
    public GiftList GiftListFirstObj(String hql,Object[] param){ 
    	Integer page = 1;
    	Integer rows = 1;
        Session session = this.getCurrentSession();  
        //返回list，list里存放的是Map对象  
        Query q = session.createSQLQuery(hql);
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        ArrayList list = (ArrayList) q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
        if(list.size() <= 0){
        	return null;
        }
        Iterator it = list.iterator();
    	GiftList g = new GiftList();
    	Object[] oc = (Object[])it.next();
    	g.setGiveUid(Integer.valueOf(oc[0].toString()));
    	g.setTotalNumber(oc[1].toString());
    	g.setPropIcon(oc[2].toString());
    	g.setPropName(oc[3].toString());
        return g;  
    } 
    
    public List<GiveAwayGiftList> GiveAwayGiftListObjList(String hql,Object[] param,Integer page,Integer rows){  
    	if (page == null || page < 1) {  
            page = 1;  
        }  
        if (rows == null || rows < 1) {  
            rows = 10;  
        }  
    	//page++;
        Session session = this.getCurrentSession();  
        //返回list，list里存放的是Map对象  
        Query q = session.createSQLQuery(hql);
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        ArrayList list = (ArrayList) q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
        Iterator it = list.iterator();
        List<GiveAwayGiftList> giveAwayGiftList= new ArrayList<>();
        while(it.hasNext()){
        	Object[] oc = (Object[])it.next();
        	GiveAwayGiftList g = new GiveAwayGiftList();
        	g.setGiveUid(Integer.valueOf(oc[0].toString()));
        	g.setTotalPopularityValue(oc[1].toString());
        	g.setGiveUidName(oc[2].toString());
        	g.setGiveUidImgUrl(oc[3].toString());
        	giveAwayGiftList.add(g);
        }
        return giveAwayGiftList;  
    } 
    
    public GiveAwayGiftList GiveAwayGiftListObj(String hql,Object[] param){ 
    	Integer page = 1;
    	Integer rows = 1;
        Session session = this.getCurrentSession();  
        //返回list，list里存放的是Map对象  
        Query q = session.createSQLQuery(hql);
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }  
        ArrayList list = (ArrayList) q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
        if(list.size() <= 0){
        	return null;
        }
        GiveAwayGiftList g = new GiveAwayGiftList();
        Iterator it = list.iterator();
    	Object[] oc = (Object[])it.next();
    	g.setGiveUid(Integer.valueOf(oc[0].toString()));
    	g.setTotalPopularityValue(oc[1].toString());
    	g.setGiveUidName(oc[2].toString());
    	g.setGiveUidImgUrl(oc[3].toString());
        return g;  
    } 
    /**
     * 只适用与查询本地榜
     * @param sql
     * @param param
     * @return
     */
    public List<RankModel> getLocalRank(String sql,Object[] param){
    	System.err.println(sql);
    	Session session = this.getCurrentSession();
    	Query q = session.createSQLQuery(sql);
        if (param != null && param.length > 0) {  
            for (int i = 0; i < param.length; i++) {  
                q.setParameter(i, param[i]);  
            }  
        }
        q.setMaxResults(50);
        ArrayList<Object> list =(ArrayList<Object>) q.list();
		if (list.size()>0){
			ArrayList<RankModel> newList = new ArrayList<RankModel>();
			for (Iterator<Object> it = list.iterator();it.hasNext();){
				Object[] ob = (Object[]) it.next();
				RankModel rank = new RankModel();
				rank.setTapesId((int)ob[0]);
				rank.setUid((int)ob[1]);
				rank.setChapter(ob[2].toString());
				rank.setNickName(ob[3].toString());
				rank.setImgUrl(ob[4].toString());
				rank.setWeeklyGifts((int)ob[5]);
				rank.setWeeklyListend((int)ob[6]);
				rank.setWeeklyTotalGifts((int)ob[7]);
				rank.setWeeklyTotalListend((int)ob[8]);
				rank.setTotalGifts((int)ob[9]);
				rank.setTotalListend((int)ob[10]);
				newList.add(rank);
			}
			return newList;
		}
        return null;
    }
    /**
     * 只适用与查询全国榜
     * @param sql
     * @param param
     * @return
     */
	public List<RankModel> getTotalRank(String sql) {
    	Session session = this.getCurrentSession();
    	Query q = session.createSQLQuery(sql);
        q.setMaxResults(50);
        ArrayList<Object> list =(ArrayList<Object>) q.list();
		if (list.size()>0){
			ArrayList<RankModel> newList = new ArrayList<RankModel>();
			for (Iterator<Object> it = list.iterator();it.hasNext();){
				Object[] ob = (Object[]) it.next();
				RankModel rank = new RankModel();
				rank.setTapesId((int)ob[0]);
				rank.setUid((int)ob[1]);
				rank.setChapter(ob[2].toString());
				rank.setNickName(ob[3].toString());
				rank.setImgUrl(ob[4].toString());
				rank.setWeeklyGifts((int)ob[5]);
				rank.setWeeklyListend((int)ob[6]);
				rank.setWeeklyTotalGifts((int)ob[7]);
				rank.setWeeklyTotalListend((int)ob[8]);
				rank.setTotalGifts((int)ob[9]);
				rank.setTotalListend((int)ob[10]);
				newList.add(rank);
			}
			return newList;
		}
        return null;
	}
    /**
     * 分页查询评论
     * @param sql
     * @param begin
     * @param count
     * @param tapesId
     * @return
     */
	public List<UserCommentVo> getComment(String sql,int begin, int count, int tapesId){
		Session session = this.getCurrentSession();
    	Query q = session.createSQLQuery(sql);
        q.setMaxResults(count);
        q.setFirstResult(begin);
        q.setParameter(0, tapesId);
        ArrayList<Object> list =(ArrayList<Object>) q.list();
		if (list.size()>0){
			ArrayList<UserCommentVo> newList = new ArrayList<UserCommentVo>();
			for (Iterator<Object> it = list.iterator();it.hasNext();){
				Object[] ob = (Object[]) it.next();
				UserCommentVo comment = new UserCommentVo();
				comment.setId((int) ob[0]);
				comment.setCommitDate(ob[1].toString());
				comment.setTapesId((int) ob[2]);
				comment.setUid((int)ob[3]);
				comment.setUserComment(ob[4].toString());
				newList.add(comment);
			}
			return newList;
		}
        return null;
	}
	public List<TapesRecordsVo> getTapesForCount(String sql, int start, int total, int uid) {
		Session session = this.getCurrentSession();
    	Query q = session.createSQLQuery(sql);
        q.setMaxResults(total);
        q.setFirstResult(start);
        q.setParameter(0, uid);
        ArrayList<Object> list =(ArrayList<Object>) q.list();
     		if (list.size()>0){
     			ArrayList<TapesRecordsVo> newList = new ArrayList<TapesRecordsVo>();
     			for (Iterator<Object> it = list.iterator();it.hasNext();){
     				Object[] ob = (Object[]) it.next();
     				TapesRecordsVo tr = new TapesRecordsVo();
     				tr.setId((int)ob[0]);
     				tr.setChapter(ob[1].toString());
     				tr.setCommitTime(ob[2].toString());
     				tr.setFlag(ob[3].toString());
     				tr.setSize((int)ob[4]);
     				tr.setTapes(ob[5].toString());
     				tr.setTop(ob[6]==null?"":ob[6].toString());
     				tr.setUid((int)ob[7]);
     				tr.setUserComment(ob[8].toString());
     				newList.add(tr);
     			}
     			return newList;
     		}
             return null;
	}
	public List<TapesRecordsVo> getTapesForCount(String sql, int start, int total, int userid, String date) {
		Session session = this.getCurrentSession();
    	Query q = session.createSQLQuery(sql);
        q.setMaxResults(total);
        q.setFirstResult(start);
        q.setParameter(0, userid);
        q.setParameter(1, date);
        ArrayList<Object> list =(ArrayList<Object>) q.list();
     		if (list.size()>0){
     			ArrayList<TapesRecordsVo> newList = new ArrayList<TapesRecordsVo>();
     			for (Iterator<Object> it = list.iterator();it.hasNext();){
     				Object[] ob = (Object[]) it.next();
     				TapesRecordsVo tr = new TapesRecordsVo();
     				tr.setId((int)ob[0]);
     				tr.setChapter(ob[1].toString());
     				tr.setCommitTime(ob[2].toString());
     				tr.setFlag(ob[3].toString());
     				tr.setSize((int)ob[4]);
     				tr.setTapes(ob[5].toString());
     				tr.setTop(ob[6].toString());
     				tr.setUid((int)ob[7]);
     				tr.setUserComment(ob[8].toString());
     				newList.add(tr);
     			}
     			return newList;
     		}
             return null;
	}
	public List<UserCommentVo> getComment(String sql, int start, int total, int tapesId, String date) {
		Session session = this.getCurrentSession();
    	Query q = session.createSQLQuery(sql);
        q.setMaxResults(total);
        q.setFirstResult(start);
        q.setParameter(0, tapesId);
        q.setParameter(1, date);
        ArrayList<Object> list =(ArrayList<Object>) q.list();
		if (list.size()>0){
			ArrayList<UserCommentVo> newList = new ArrayList<UserCommentVo>();
			for (Iterator<Object> it = list.iterator();it.hasNext();){
				Object[] ob = (Object[]) it.next();
				UserCommentVo comment = new UserCommentVo();
				comment.setId((int) ob[0]);
				comment.setCommitDate(ob[1].toString());
				comment.setTapesId((int) ob[2]);
				comment.setUid((int)ob[3]);
				comment.setUserComment(ob[4].toString());
				newList.add(comment);
			}
			return newList;
		}
        return null;
	}
}
